<?php


namespace App\Lib\Check;

use EasySwoole\Jwt\Jwt;
/**
 * Trait Node api App接口授权 jwt 验证
 * @package App\HttpController\Api
 */
trait Authorize{

   private $appid;
   private $appsecret;

   public function setConfig($appid,$appsecret){
       $this->appid = $appid;
       $this->appsecret = $appsecret;
   }

    /**
     * @title 创建token
     * @return false|string
     * Created by PhpStorm
     * User: shanshui
     * Date: 2020/3/19
     * Time: 10:53
     */
   public function createToken($user = USER_SESSION_NOT_LOGIN,$version = '1.0.0',$channel = 'App Store',$idfa = 'XXXXXXXX',$device = 'iPhone 11'){

       $jwtObject = Jwt::getInstance()
           ->setSecretKey($this->appsecret) // 秘钥
           ->publish();

       $jwtObject->setAlg('HMACSHA256'); // 加密方式
       $jwtObject->setAud($user); // 用户
       $jwtObject->setExp(time()+APP_SESSION_TIME_OUT); // 过期时间
       $jwtObject->setIat(time()); // 发布时间
       $jwtObject->setIss('shanshui'); // 发行人
       $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
       $jwtObject->setNbf(time()); // 在此之前不可用
       $jwtObject->setSub('easyswoole-api'); // 主题
       // 自定义数据
       $jwtObject->setData([
           'version'=>$version,   //版本
           'channel'=>$channel, //渠道
           'device'=>$device, //设备
           'idfa'=>$idfa, //唯一表示
       ]);
       // 最终生成的token
       $token = $jwtObject->__toString();

       return $token;
   }

    /**
     * @title 解析token
     * @param $token
     * @return array
     * Created by PhpStorm
     * User: shanshui
     * Date: 2020/3/19
     * Time: 10:53
     */
   public function decryptToken($token){
       try {

           $jwtObject = Jwt::getInstance()->setSecretKey($this->appsecret)->decode($token);
           $status = $jwtObject->getStatus();
           $error = '';
           $result = [];
           switch ($status)
           {
               case  1:
                   $result['user'] = $jwtObject->getAud();
                   $result['add_time'] = $jwtObject->getNbf();
                   $result['expire_time'] = $jwtObject->getExp();;
                   $result['data'] = $jwtObject->getData();
                   /*$jwtObject->getAlg();
                   $jwtObject->getIat();
                   $jwtObject->getIss();
                   $jwtObject->getJti();
                   $jwtObject->getSub();
                   $jwtObject->getSignature();
                   $jwtObject->getProperty('alg');*/
                   break;
               case  -1:
                   $error= '无效';
                   break;
               case  -2:
                   $error = 'token过期';
                   break;
           }
           return $error == ''? ['status'=>$status,'result'=>$result] : ['status'=>$status,'error'=>$error];
       } catch (\EasySwoole\Jwt\Exception $e) {
              return [$e->getMessage()];
       }


   }
}